# -*- coding: utf-8 -*-
"""
Created on Fri Aug  2 15:15:30 2024

@author: xiaobojie
"""

'''
完成1个任务，如果需要多个步骤，则封装为class,每个步骤封装为方法
如果需要1个步骤，则封装为函数
'''

#%%
'''
按明细表重命名pdf和x_t
面向对象
优先使用
'''
import pandas as pd
import os
import shutil
import re

class FileProcessor:
    def __init__(self, directory, csv_file, file_pattern, file_extension):
        self.directory = directory
        self.csv_file = csv_file
        self.file_pattern = file_pattern
        self.file_extension = file_extension
    
    def replace_tabs_with_commas(self, input_file, output_file):
        """
        将txt文件中的\t替换为,
        转为csv
        """
        try:
            # 读取txt文件
            with open(os.path.join(self.directory, input_file), 'r', encoding='utf-8') as file:
                content = file.read()

            # 将制表符替换为逗号
            content = content.replace('\t', ',')

            # 将替换后的内容写入新的文件
            with open(os.path.join(self.directory, output_file), 'w', encoding='utf-8') as file:
                file.write(content)

            print(f"File with replaced content saved as {output_file}")
        except Exception as e:
            print(f"An error occurred: {e}")

    def process_csv(self, input_file, output_file):
        """
        处理csv中的文本，符合重命名要求
        """
        try:
            # 读取CSV文件
            f = pd.read_csv(os.path.join(self.directory, input_file))

            # 打印列名以供检查
            print("Columns in CSV file:", f.columns)

            # 检查是否存在 'Descriptive Part Name' 列
            if 'Descriptive Part Name' not in f.columns:
                print("Error: Column 'Descriptive Part Name' not found in the CSV file.")
                return

            # 数据清理
            f.replace(r'^\s+', '', regex=True, inplace=True)  # 删除单元格前缩进
            f.replace(r'\sx.*?,', '', regex=True, inplace=True)  # 删除单元格后x数量
            f.drop_duplicates('Descriptive Part Name', keep='first', inplace=True)  # 删除重复
            f.sort_values(by='Descriptive Part Name', inplace=True, ascending=True)  # 排序时，大写字母会排在前面

            # 保存处理后的CSV文件
            f.to_csv(os.path.join(self.directory, output_file), encoding='utf_8_sig', index=False)
            print(f"Processed file saved as {output_file}")
        except Exception as e:
            print(f"An error occurred: {e}")

    def move_and_rename_files(self):
        """
        移动并重命名文件
        """
        try:
            # 获取匹配的文件
            matched_files = [f for f in os.listdir(self.directory) if re.match(self.file_pattern, f)]
            matched_files.sort(key=str.lower)

            # 读取 CSV 文件
            csv_data = pd.read_csv(os.path.join(self.directory, self.csv_file))

            # 处理文件
            for file in matched_files:
                part_number = file.split('.')[0]  # 从文件名提取物料号
                print(f"Processing file: {part_number}")

                # 查找 CSV 中的匹配行
                # 将 过滤  条件放在同一行
                matching_rows = csv_data[csv_data['Descriptive Part Name'] == part_number]
                if not matching_rows.empty:
                    
                    # iterrows() 是 Pandas DataFrame 的一种迭代方法，允许逐行遍历 DataFrame 的行数据。
                    # 返回值：iterrows() 返回一个生成器，其中每个迭代步骤返回一个二元组 (index, Series)，其中：
                    # index 是行标签（通常是整数索引）。
                    # Series 是包含行数据的 Pandas Series 对象。
                    for _, row in matching_rows.iterrows():
                        if row['ccode'][0] == '0':  # 检测 ccode 首位是否为 '0'
                            new_filename = f"{row['ccode']} #{row['cname']}# {row['crevi']}{self.file_extension}"
                        else:
                            new_filename = f"0{row['ccode']} #{row['cname']}# {row['crevi']}{self.file_extension}"
                        print(f"Renaming and moving file to: {new_filename}")
                        
                        try:
                            shutil.move(os.path.join(self.directory, file), os.path.join(self.directory, new_filename))
                        except Exception as e:
                            print(f"Error moving file {file} to {new_filename}: {e}")
                else:
                    print(f"No matching CSV entry found for {part_number}")

            print("File renaming and moving completed.")
        except Exception as e:
            print(f"An error occurred: {e}")

if __name__ == "__main__":
    directory = 'Z:/virtual_share/图纸修改'
    csv_f = 'new 2.txt'
    csv_o = 'new 2o.csv'
    file_pattern = r'.*x_t'
    file_extension = '.x_t'

    processor = FileProcessor(directory, csv_o, file_pattern, file_extension)
    
    # 替换制表符并保存为csv
    processor.replace_tabs_with_commas(csv_f, csv_o)
    
    # 处理csv文件
    processor.process_csv(csv_f, csv_o)
    
    # 移动并重命名文件
    processor.move_and_rename_files()







#%%

'''
按明细表重命名pdf和x_t
函数封装
仅学习
'''



import pandas as pd
import os, shutil, re


def replace_tabs_with_commas(input_path, input_file, output_file):
    '''
    将txt文件中的\t替换为,
    转为csv
    '''
    
    try:
        # 设置工作目录
        os.chdir(input_path)

        # 读取txt文件
        with open(input_file, 'r', encoding='utf-8') as file:
            content = file.read()

        # 将制表符替换为逗号
        content = content.replace('\t', ',')

        # 将替换后的内容写入新的文件
        with open(output_file, 'w', encoding='utf-8') as file:
            file.write(content)

        print(f"File with replaced content saved as {output_file}")
    except Exception as e:
        print(f"An error occurred: {e}")

def process_csv(input_path, input_file, output_file):
    '''
    处理csv中的文本，符合重命名要求
    '''
    
    try:
        # 设置工作目录
        os.chdir(input_path)

        # 读取CSV文件
        f = pd.read_csv(input_file)

        # 打印列名以供检查
        print("Columns in CSV file:", f.columns)

        # 检查是否存在 'Descriptive Part Name' 列
        if 'Descriptive Part Name' not in f.columns:
            print("Error: Column 'Descriptive Part Name' not found in the CSV file.")
            return

        # 数据清理
        f.replace(r'^\s+', '', regex=True, inplace=True)  # 删除单元格前缩进
        f.replace(r'\sx.*?,', '', regex=True, inplace=True)  # 删除单元格后x数量
        f.drop_duplicates('Descriptive Part Name', keep='first', inplace=True)  # 删除重复
        f.sort_values(by='Descriptive Part Name', inplace=True, ascending=True)  # 排序时，大写字母会排在前面

        # 保存处理后的CSV文件
        f.to_csv(output_file, encoding='utf_8_sig')
        print(f"Processed file saved as {output_file}")
    except Exception as e:
        print(f"An error occurred: {e}")
        
        
def move_and_rename_files(directory, file_pattern, file_extension, csv_filename):
    # 更改当前工作目录
    os.chdir(directory)

    # 获取匹配的文件
    matched_files = [f for f in os.listdir('.') if re.match(file_pattern, f)]
    matched_files.sort(key=str.lower)

    # 读取 CSV 文件
    csv_data = pd.read_csv(csv_filename)

    # 处理文件
    for file in matched_files:
        part_number = file.split('.')[0]  # 从文件名提取物料号
        print(f"Processing file: {part_number}")

        # 查找 CSV 中的匹配行
        matching_rows = csv_data[csv_data['Descriptive Part Name'] == part_number]
        if not matching_rows.empty:
            for _, row in matching_rows.iterrows():
                if row['ccode'][0] == '0':  # 检测 ccode 首位是否为 '0'
                    new_filename = f"{row['ccode']} #{row['cname']}# {row['crevi']}{file_extension}"
                else:
                    new_filename = f"0{row['ccode']} #{row['cname']}# {row['crevi']}{file_extension}"
                print(f"Renaming and moving file to: {new_filename}")
                
                try:
                    shutil.move(file, new_filename)
                except Exception as e:
                    print(f"Error moving file {file} to {new_filename}: {e}")
        else:
            print(f"No matching CSV entry found for {part_number}")

    print("File renaming and moving completed.")

if __name__ == "__main__":
    path = 'Z:/virtual_share/图纸修改'
    csv_f = 'new 2.txt'
    csv_o = 'new 2o.csv'
    process_csv(path, csv_f, csv_o)
    
    directory = 'Z:/virtual_share/图纸修改'
    file_pattern = r'.*x_t'
    file_extension = '.x_t'
    csv_filename = 'new 2o.csv'
    
    move_and_rename_files(directory, file_pattern, file_extension, csv_filename)
    
#%%

'''
按明细表重命名pdf和x_t
未封装
仅学习
'''

# 处理重命名表格


import pandas as pd

# path = 'D:/主被动归档/主被动_图纸归档_11'

# path = 'D:\主被动归档\主被动1.5_图纸归档_3'
# path = 'C:/Users/xiaobojie/Desktop/图纸外发/pl231121 电动手柄加工'
# path = 'C:/Users/xiaobojie/Desktop/图纸外发/主被动1.5代 修改底座上肢架'
path = 'Z:/virtual_share/图纸修改'


os.chdir(path)
# print(os.getcwd())


# 处理ug导出的csv文件
csv_f = 'new 2.txt'
csv_o = 'new 2o.csv'
f = pd.read_csv(csv_f)

f.replace(r'^\s+', '', regex=True, inplace=True) #删除单元格前缩进
f.replace(r'\sx.*?$', '', regex=True, inplace=True) #删除单元格后x数量
f.drop_duplicates('Descriptive Part Name', keep='first', inplace=True) #删除重复
f.sort_values(by='Descriptive Part Name', inplace=True, ascending=True) #排序时，大写字母会排在前面
f.to_csv(csv_o, encoding='utf_8_sig')





# 将pdf文件，对照表格内容重命名

import os, re, shutil
import pandas as pd

# path = 'D:/主被动归档/主被动_图纸归档_11'

# path = 'D:\主被动归档\主被动1.5_图纸归档_3'

# path = 'C:/Users/xiaobojie/Desktop/图纸外发/pl231121 电动手柄加工'

# path = 'C:/Users/xiaobojie/Desktop/图纸外发/主被动1.5代 修改底座上肢架'
path = 'Z:/virtual_share/图纸修改'
os.chdir(path)

# re_str = r'.*pdf'
# ext_name = '.pdf'

re_str = r'.*x_t'
ext_name = '.x_t'

csv_o = 'new 2o.csv'


pdf_files = []
# xt_files = []
for f in os.listdir('.'):
    if re.match(re_str, f):
        pdf_files.append(f)
    # elif re.match(r'.*x_t', f):
    #     x_t_files.append(f)
pdf_files.sort(key=str.lower)
# x_t_files.sort(key=str.lower)
# print(pdf_files)
# print(len(pdf_files))
# print(x_t_files)


g = pd.read_csv(csv_o)

for i in range(len(pdf_files)): 
    a = pdf_files[i].split('.')[0] # 从文件名提取物料号
    print(a)
    # print(pdf_files[i])

    for j in range(len(g)): 
        if g['Descriptive Part Name'][j] == a: 
            if g['ccode'][j][0] == '0': # 检测ccode首0是否被删除，
                b = g['ccode'][j]+' #'+g['cname'][j]+'# '+g['crevi'][j]+ext_name  
            else:
                b = '0'+g['ccode'][j]+' #'+g['cname'][j]+'# '+g['crevi'][j]+ext_name
            print(b)  
            shutil.move(pdf_files[i], b)
        j = j+1
    i = i+1
